<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Validate;
use think\Db;
use think\Log;
use think\Exception;
use app\admin\model\VDayOrder;
use app\admin\model\VDayUser;
use app\admin\model\VDayAgency;
use app\admin\model\VAnnalRoom;
use function GuzzleHttp\json_encode;
use app\admin\model\VDayRoom;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login','delsql','delodersql','statisticsday'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 后台首页
     */
    public function index()
    {
        //
        $menulist = $this->auth->getSidebar([
            'dashboard' => 'hot',
            'addon'     => ['new', 'red', 'badge'],
            'auth/rule' => 'side',
            'general'   => ['18', 'purple'],
                ], $this->view->site['fixedpage']);
        $this->view->assign('menulist', $menulist);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin())
        {
            $this->error(__("You've logged in, do not login again"), $url);
        }
        if ($this->request->isPost())
        {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule);
            $result = $validate->check($data);
            if (!$result)
            {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            \app\admin\model\AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 0);
            if ($result === true)
            {
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            }
            else
            {
                $this->error(__('Username or password is incorrect'), $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin())
        {
            $this->redirect($url);
        }
        \think\Hook::listen("login_init", $this->request);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'), 'index/login');
    }
    
    /**
     * 每天清除五天前的游戏记录失败
     */
    public function delsql(){
        $res = Db::query("DELETE FROM fa_v_annal_game where ( FROM_UNIXTIME(createtime/1000,'%Y-%m-%d %H:%I:%S') < date_sub(now(),interval 5 day) )");
        if($res === false){
            Log::write('操作：每天清除五天前的游戏记录失败');
            return false;
        }
        return true;
    }
    
    /**
     * 每天清除（32天前+客户端+未支付+没在游戏添加房卡）订单记录
     * @author violet
     * @since 2017-12-20
     */
    public function delodersql(){
        $res = Db::query("select * FROM fa_y_onlineorder where ( FROM_UNIXTIME(addtime/1000,'%Y-%m-%d %H:%I:%S') < date_sub(now(),interval 32 day) and (channel=2) and (status=0) and (isgame=0))");
        try
        {
            $oid_array = array_column($res, 'ID');
            Db::table('fa_y_ordergoods')->where(['oid'=>array('in',$oid_array)])->delete();
            Db::table('fa_y_orderlog')->where(['oid'=>array('in',$oid_array)])->delete();
            Db::table('fa_y_onlineorder')->where(['ID'=>array('in',$oid_array)])->delete();
        }
        catch(Exception $e)
        {
            Log::write('delodersql:'.$e->getMessage());
            return $e->getMessage();
        }
    }
    
    /**
     * 每天统计数据
     * @author violet
     * @since 2018-1-26
     */
    public function statisticsDay(){
        //昨天时间
        $y_startime = date('Y-m-d 00:00:00',strtotime('-1 day'));//昨天开始时间
        $y_endtime = date('Y-m-d 23:59:59',strtotime('-1 day'));//昨天结束时间
        $short_star = strtotime($y_startime);
        $short_end = strtotime($y_endtime);
        $long_star = $this->getMilliDate($y_startime);
        $long_end = $this->getMilliDate($y_endtime);
        
        $order_data = array();
        
        //客户端 + 支付成功 + 昨天时间 订单
        $c_order = Db::name('y_onlineorder')->field('count(*) as paynum,sum(orderamount) as amount')->where(['channel'=>2,'status'=>2])->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d') = date_sub(curdate(),interval 1 day) ")->find();
        //代理 + 支付成功 + 昨天时间 订单
        $a_order = Db::name('y_onlineorder')->field('count(*) as paynum,sum(orderamount) as amount')->where(['channel'=>1,'status'=>2])->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d') = date_sub(curdate(),interval 1 day) ")->find();
        $order_data['0']['paynum'] = empty($c_order['paynum'])?0:$c_order['paynum'];
        $order_data['0']['amount'] = empty($c_order['amount'])?0:$c_order['amount'];
        $order_data['0']['channel'] = 2;
        $order_data['0']['addtime'] = $short_star;
        $order_data['1']['paynum'] = empty($a_order['paynum'])?0:$a_order['paynum'];
        $order_data['1']['amount'] = empty($a_order['amount'])?0:$a_order['amount'];
        $order_data['1']['channel'] = 1;
        $order_data['1']['addtime'] = $short_star;
        $obj_order = new VDayOrder();
        if($obj_order->saveAll($order_data) === false){
            Log::write('statisticsDay：订单记录失败');
            return false;
        }
        
        //昨天时间 注册用户数
        $y_user = Db::connect("GameDB")->table('user')->where("FROM_UNIXTIME(createTime/1000,'%Y-%m-%d') = date_sub(curdate(),interval 1 day) ")->count();//昨天注册用户
        $c_user = Db::connect("GameDB")->table('user')->where("FROM_UNIXTIME(createTime/1000,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') ")->count();//今天之前
        $user           = new VDayUser();
        $user->createtime  = $short_star;
        $user->registernum = $y_user;
        $user->totalnum    = $c_user;
        if($user->save() === false){
            Log::write('statisticsDay：注册用户记录失败');
            return false;
        }
        
        //今日房卡消耗(大厅+俱乐部)
        $roomcode = Db::name('v_annal_room')->where("FROM_UNIXTIME(endtime/1000,'%Y-%m-%d') = date_sub(curdate(),interval 1 day)")->sum('roomcode'); //昨天消耗房卡
        $kinidroom = Db::query("SELECT kinId,COUNT(*) AS num FROM (
             SELECT `kinId`,`roomid`,count(*) FROM `fa_v_annal_room` WHERE ( roomcode > 0 and FROM_UNIXTIME(endtime/1000,'%Y-%m-%d') = date_sub(curdate(),interval 1 day) ) GROUP BY roomid,createtime 
        ) `_group_count_` group by kinId");
        if(empty($kinidroom)){
            $roomnum = 0;
        }
        $dayroom           = new VDayRoom();
        $dayroom->createtime  = $short_star;
        $dayroom->gameroom = json_encode($kinidroom);
        $dayroom->roomnum = empty($kinidroom)?0:array_sum(array_column($kinidroom, 'num'));
        $dayroom->diamond = $roomcode;
        if($dayroom->save() === false){
            Log::write('statisticsDay：开房记录失败');
            return false;
        }
        
        
        //昨天时间 代理统计
//         $y_agency = Db::table('fa_y_agency')->field('LevelID,count(*) as today_num,sum(money) as money')->where("DATE_FORMAT(RegisterTime,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d')  ")->group('LevelID')->select();//今天之前代理
//         $promotionincome = Db::name('y_promotionincome')->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') ")->sum('money');//提成
//         $withdrawals = Db::name('y_withdrawals')->where(['status'=>array('in',[0,1])])->where("FROM_UNIXTIME(addtime/1000,'%Y-%m-%d') < date_format(now(),'%Y-%m-%d') ")->sum('money');//提现
//         $agency           = new VDayAgency();
//         $agency->createtime = $short_star;
//         $agency->money = 0;
//         foreach ($y_agency as $key=>$val){
//             if($val['LevelID'] == 1){
//                 $agency->onegrade  = $val['today_num'];
//                 $agency->money = $agency->money + $val['money'];
//             }
//             if($val['LevelID'] == 2){
//                 $agency->twograde  = $val['today_num'];
//                 $agency->money = $agency->money + $val['money'];
//             }
//             if($val['LevelID'] == 3){
//                 $agency->threegrade  = $val['today_num'];
//                 $agency->money = $agency->money + $val['money'];
//             }
//         }
//         $agency->promotionincome = $promotionincome?:0;
//         $agency->withdrawals    = $withdrawals?:0;
//         if($agency->save() === false){
//             Log::write('statisticsDay：代理记录失败');
//             return false;
//         }
        
        return true;
    }

}
